<template>
	<el-table
		border
		stripe
		max-height="500"
		empty-text="无结果"
		style="width: 100%"
		:data="filterTableData"
		@cell-click="cellClick"
	>
		<el-table-column label="标题">
			<template #header v-if="enableSearch">
				<el-input
					v-model="search.title"
					:placeholder="placeholder.title"
					class="search-input"
					clearable
				/>
			</template>

			<template #default="scope">
				<div class="video-table-item">
					<p
						v-if="editItemKey != scope.row.key"
						@click="clickItem(scope.$index, scope.row)"
					>
						{{ scope.row.title }}
					</p>
					<el-input v-else v-model="editTitle" placeholder="Please input" />
					<el-button
						size="small"
						v-if="editItemKey != scope.row.key"
						@click="changeVideoName(scope.$index, scope.row)"
					>
						修改
					</el-button>
					<el-button
						v-else
						size="small"
						@click="confirmChangeVideoName(scope.$index, scope.row)"
					>
						完成
					</el-button>
				</div>
			</template>
		</el-table-column>

		<el-table-column prop="tags" label="标签" min-width="100">
			<template #default="scope">
				<tags-controller
					:tags="scope.row.tags"
					:showDelete="props.showDelete"
					@delete="deleteItem(scope.row.key)"
					@change="(msg) => changeTags(scope.row.key, msg)"
				/>
			</template>
		</el-table-column>
	</el-table>
</template>

<script lang="ts" setup>
import { useRouter } from "vue-router";
import { useConfig } from "@/store/config";
import { useWindow } from "@/utils/useWindow";
import { defineProps, reactive, computed, ref } from "vue";
import tagsController from "@/components/common/tags-controller.vue";
import { deleteItem, fetchEditVideoTitle, IMP3Data } from "@/utils/useRequest";
import { changeTagsHandler, IChangeTagMsg } from "@/utils/tag";
import { ElNotification } from "element-plus";

interface ITableCellInfo {
	key: string;
	type: string;
	order: string;
	property: keyof IMP3Data;
}

const emit = defineEmits(["click"]);

const props = defineProps({
	tableData: {
		type: Array,
		default: () => [],
	},
	enableSearch: {
		type: Boolean,
		default: true,
	},
	showDelete: {
		type: Boolean,
		default: true,
	},
});

const router = useRouter();

const search = reactive({
	title: "",
});

const editItemKey = ref("");
const editTitle = ref("");
const { width } = useWindow();
const { mp3ByID } = useConfig();

const placeholder = computed(() =>
	width.value > 476 ? { title: "检索标题" } : { title: "标题" }
);

const filterTableData = computed(() => {
	return (props.tableData as unknown as IMP3Data[])
		.filter((item) => item.mediatype !== "AUDIO")
		.filter(({ title }) => title.includes(search.title)) as IMP3Data[];
});

function cellClick(data: IMP3Data, info: ITableCellInfo) {
	const key = info.property;

	if (key === "title") {
		const query = mp3ByID
			? { key: data.key }
			: {
					title: data.title,
			  };
		router.push({ query });
	} else {
		router.push({
			query: { [key]: data[key] },
		});
	}
}

function changeTags(key: string, msg: IChangeTagMsg) {
	changeTagsHandler(msg, key);
}

function changeVideoName(_index: number, data: IMP3Data) {
	editTitle.value = data.title;
	editItemKey.value = data.key;
}

function confirmChangeVideoName(_index: number, data: IMP3Data) {
	if (editTitle.value === data.title) {
		editItemKey.value = "";
		ElNotification({
			type: "info",
			message: "未修改标题名：" + data.title,
		});
		return;
	} else {
		const { key } = data;
		const title = editTitle.value;

		function failToEdit(error: any) {
			ElNotification({
				type: "error",
				message: `修改标题失败，代码：${error}`,
			});
		}
		fetchEditVideoTitle({ key, title })
			.then((res) => {
				if (res.code === 200) {
					ElNotification({
						type: "success",
						message: `成功修改标题为：${title}`,
					});
				} else {
					failToEdit(res.code);
				}
			})
			.catch((err) => failToEdit(err))
			.finally(() => {
				editItemKey.value = "";
				data.title = title;
			});
	}
}

function clickItem(index: number, data: IMP3Data) {
	emit("click", { index, data });
}
</script>

<style lang="less">
.search-input {
	width: 100% !important;
	input {
		width: 100% !important;
	}
}

div.video-table-item {
	display: flex;
	align-items: center;
	flex-direction: row;
	justify-content: space-between;
	input {
		width: 95% !important;
	}
}
</style>
